<template>
  <div class="message-window" :class="{ 'message-window--expanded': isExpanded }">
    <div class="message-window__trigger" :class="{ 'message-window__trigger--has-unread': unreadCount > 0 }" @click="toggleExpand">
      <el-badge :value="unreadCount" :max="99" class="message-badge">
        <el-icon :size="24"><Bell /></el-icon>
      </el-badge>
    </div>

    <div v-show="isExpanded" class="message-window__content">
      <div class="message-window__header">
        <span>未读消息</span>
        <el-button link @click="goToMessageList" style="color:var(--el-color-primary)">查看更多</el-button>
      </div>
      
      <div class="message-window__list">
        <template v-if="messages.length">
          <el-tooltip
            v-for="msg in messages"
            :key="msg.messageId"
            :content="msg.messageTitle"
            placement="right"
            :effect="'dark'"
            :max-width="300"
            :show-after="200"
          >
            <div class="message-item" @click="handleMessageClick(msg)">
              <div class="message-item__tags">
                <el-tag size="small" :type="msg.priority">{{ msg.messagePriorityText }}</el-tag>
                <el-tag size="small" type="info">{{ msg.messageTypeText }}</el-tag>
              </div>
              <div class="message-item__main">
                <div class="message-item__title">{{ msg.messageTitle }}</div>
                <div class="message-item__time">{{ msg.messageTime }}</div>
              </div>
            </div>
          </el-tooltip>
        </template>
        <el-empty v-else description="暂无未读消息" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { Bell } from '@element-plus/icons-vue'
import { useMessageStore } from '@/store/modules/message'
import { getUnreadCount, getUnreadMessages, markMessageRead } from '@/api/system/message'
import { ElMessage } from 'element-plus'

const router = useRouter()
const messageStore = useMessageStore()
const isExpanded = ref(false)
const unreadCount = ref(0)
const messages = ref([])
// let timer: NodeJS.Timer | null = null

// 获取未读消息数量
const fetchUnreadCount = async () => {
  let heartbeatTimer = null
  let lastHeartbeatTime = Date.now()
  const HEARTBEAT_INTERVAL = 60000 // 60秒检查一次心跳
  const HEARTBEAT_TIMEOUT = 90000 // 90秒没有心跳则重连

  const connect = () => {
    const eventSource = new EventSource('/api/system/message/unread/rt?token=' + sessionStorage.getItem('Authorization'))

    eventSource.onmessage = function(event) {
      lastHeartbeatTime = Date.now()
      const count = parseInt(event.data)
      if (!isNaN(count)) {
        messageStore.updateUnreadCount(count)
        unreadCount.value = count
      }
    }

    eventSource.onerror = function(err) {
      console.error('SSE 连接异常:', err)
      eventSource.close()
      setTimeout(connect, 5000) // 5秒后重试连接
    }

    eventSource.addEventListener('open', () => {
      console.log('SSE 连接已建立')
      // 启动心跳检测
      heartbeatTimer = setInterval(() => {
        const now = Date.now()
        if (now - lastHeartbeatTime > HEARTBEAT_TIMEOUT) {
          console.warn('SSE 心跳超时，准备重连')
          clearInterval(heartbeatTimer)
          eventSource.close()
          connect()
        }
      }, HEARTBEAT_INTERVAL)
    })

    return eventSource
  }

  const eventSource = connect()

  // 返回清理函数
  return () => {
    if (heartbeatTimer) {
      clearInterval(heartbeatTimer)
    }
    eventSource.close()
  }
}

// 获取未读消息列表
const fetchUnreadMessages = async () => {
  try {
    const res = await getUnreadMessages()
    messageStore.updateMessages(res.data)
    messages.value = res.data
  } catch (error) {
    console.error('获取未读消息列表失败:', error)
  }
}

// 点击浮窗外部关闭
const handleClickOutside = (event: MouseEvent) => {
  const messageWindow = document.querySelector('.message-window')
  if (messageWindow && !messageWindow.contains(event.target as Node) && isExpanded.value) {
    isExpanded.value = false
  }
}

// 切换展开/收起状态
const toggleExpand = () => {
  isExpanded.value = !isExpanded.value
  if (isExpanded.value) {
    fetchUnreadMessages()
  }
}

// 跳转到消息列表页面
const goToMessageList = () => {
    isExpanded.value = false
    router.push('/message/list')
}

// 处理消息状态变更
const handleStatusChange = () => {
  // fetchUnreadCount()
  if (isExpanded.value) {
    fetchUnreadMessages()
  }
}

// 点击消息
const handleMessageClick = async (msg: any) => {
    try {
        await markMessageRead(msg.messageId)
    } catch (error) {
        console.error('标记已读失败:', error)
    }
    handleStatusChange()
    ElMessage.error('需补充跳转对应业务页面的逻辑')
}

// 初始化定时获取未读消息数量
onMounted(() => {
  fetchUnreadCount()
  document.addEventListener('click', handleClickOutside)
  // 监听消息状态变更事件
  window.addEventListener('message-status-change', handleStatusChange)
})

// 组件销毁时清理定时器和事件监听
onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
  window.removeEventListener('message-status-change', handleStatusChange)
})
</script>

<style lang="scss" scoped>
.message-window {
  position: fixed;
  left: 20px;
  bottom: 20px;
  z-index: 2000;

  &__trigger {
    cursor: pointer;
    background: var(--el-color-primary);
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .el-icon {
      animation: none;
    }

    &--has-unread .el-icon {
      animation: bell-shake 1s ease-in-out infinite;
    }
  }

  @keyframes bell-shake {
    0%, 100% {
      transform: rotate(0);
    }
    20%, 60% {
      transform: rotate(15deg);
    }
    40%, 80% {
      transform: rotate(-15deg);
    }
  }

  &__content {
    position: absolute;
    left: 0;
    bottom: 50px;
    width: 300px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  &__header {
    padding: 12px 16px;
    border-bottom: 1px solid var(--el-border-color-lighter);
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  &__list {
    max-height: 400px;
    overflow-y: auto;
  }
}

.message-item {
  display: flex;
  padding: 5px 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  cursor: pointer;

  &:hover {
    background-color: var(--el-color-primary-light-9);
  }

  &__tags {
    display: grid;
    gap: 8px;
  }

  &__main {
    display: flex;
    flex-direction: column;
    padding-left: 12px;
  }

  &__title {
    font-size: 14px;
    margin-bottom: 8px;
    width: 75%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  &__time {
    font-size: 12px;
    color: var(--el-text-color-secondary);
  }

  &__actions {
    display: flex;
    gap: 8px;
  }
}

.message-badge :deep(.el-badge__content) {
  z-index: 2001;
}
</style>